package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.TodayBest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TanHuaService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private QuestionService questionService;

    @Reference(version = "1.0.0",check = false)
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0",check = false)
    private VisitorsApi visitorsApi;

    @Reference(version = "1.0.0",check = false)
    private UserLocationApi userLocationApi;

    @Value("${tanhua.default.recommend.users}")
    private String defaultRecommendUsers;

    @Reference(version = "1.0.0",check = false)
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;


    public TodayBest queryUserInfo(Long userId) {

        UserInfo userInfo = this.userInfoService.querybyuserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        TodayBest todayBest = new TodayBest();
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
        todayBest.setAvatar(userInfo.getLogo());

        //缘分值
        User user = UserThreadLocal.get();
        todayBest.setFateValue(this.recommendUserService.queryScore(userId, user.getId()).longValue());

        // 记录来访用户
        // 可以调用Dubbo直接往MongoDB中插入一条记录
        // 也可以使用MQ 去发送一条消息  异步的添加
        this.visitorsApi.saveVisitor(userId, user.getId(), "个人主页");

        return todayBest;
    }

    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (ObjectUtil.isNotEmpty(question)) {
            return question.getTxt();
        }
        //默认的问题
        return "你的爱好是什么？";
    }

    public Boolean replyQuestion(Long userId, String reply) {
        // 获取当前登录用户的ID
        User user = UserThreadLocal.get();
        // 获取用户信息 其实是为了拿到用户的昵称
        UserInfo userInfo = this.userInfoService.querybyuserId(user.getId());

        /*
             {  "userId":1,
                "huanXinId":"HX_1",
                "nickname":"黑马小妹",
                "strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？",
                "reply":"我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"
             }
        */
        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId());
        msg.put("huanXinId", "HX_" + user.getId());
        // 获取昵称
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", this.queryQuestion(userId));
        msg.put("reply", reply);

        //发送环信消息
        return this.huanXinApi.sendMsgFromAdmin("HX_" + userId,
                HuanXinMessageType.TXT, JSONUtil.toJsonStr(msg));
    }


    /**
     * 搜附近的人
     * @param gender
     * @param distance
     * @return
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //查询当前用户的位置
        User user = UserThreadLocal.get();
        // 根据用户的id查询用户的位置信息
        // 需要额外的查询一次
        // 查询到的数据可能不是最新的位置信息
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        if (ObjectUtil.isEmpty(userLocationVo)) {
            return ListUtil.empty();
        }

        // 根据用户的位置信息去查询周边的人  固定查询50条记录
        PageInfo<UserLocationVo> pageInfo = this.userLocationApi.queryUserFromLocation(userLocationVo.getLongitude(),
                userLocationVo.getLatitude(),
                Convert.toDouble(distance),
                1,
                50
        );

        // records 附近人的位置信息
        List<UserLocationVo> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return ListUtil.empty();
        }

        // 构造筛选条件
        // 附件人的用户id
        //

        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        //userIdList.remove(user.getId());

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);
        // 做判断 筛选条件是否为空
        if (StrUtil.equalsIgnoreCase(gender, "man")) {
            queryWrapper.eq("sex", SexEnum.MAN);
        } else if (StrUtil.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.eq("sex", SexEnum.WOMAN);
        }

        // 查询MySQL 拿到附近的人的信息
        List<UserInfo> userInfoList = this.userInfoService.queryUserinfoList(queryWrapper);

        // 开始拼凑VO对象  ES
        List<NearUserVo> result = new ArrayList<>();
        for (UserLocationVo locationVo : records) {
            //排除自己
            if (ObjectUtil.equals(locationVo.getUserId(), user.getId())) {
                continue;
            }

            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(locationVo.getUserId(), userInfo.getUserId())) {

                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(userInfo.getUserId());// 用户ID
                    nearUserVo.setAvatar(userInfo.getLogo());// 用户的头像
                    nearUserVo.setNickname(userInfo.getNickName());//用户的昵称
                    result.add(nearUserVo);
                    break;
                }
            }
        }

        return result;
    }

    /**
     * 查询推荐卡片列表，从推荐列表中随机选取10个用户
     *
     * @return
     */
    public List<TodayBest> queryCardsList() {
        // 获取当前登录用户的ID
        User user = UserThreadLocal.get();
        int count = 50;

        // 查询到的50条数据，并不是用来直接展现，需要从这50条数据中随机返回一些数据
        // recommendUserList :  50条记录
        // 不仅仅只是用户的ID 而是推荐表中的数据
        List<RecommendUser> recommendUserList = this.recommendUserService.queryCardList(user.getId(), count);


        // 判断查询的数据是否为空 如果为空给默认值
        if (CollUtil.isEmpty(recommendUserList)) {
            recommendUserList = new ArrayList<>();
            // 默认推荐列表  10条
            // 自己推荐 根据用户的id查询到用户的userinfo 去MySQL中做查询
            // 条件是啥  条件就是我们推荐的根据  28  28左右的  性别是男  杭州  正常人的
            // 模拟大数据系统给出一些默认的推荐
            // 查询数据  分页查询
            List<String> list = StrUtil.split(defaultRecommendUsers, ',');
            for (String userId : list) {
                RecommendUser recommendUser = new RecommendUser();

                recommendUser.setToUserId(user.getId());
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUserList.add(recommendUser);
            }
        }

        //计算展现的数量，默认展现10个
        // 默认给APP返回10条  上面从mongodb中拿到50条  4条
        int showCount = Math.min(10, recommendUserList.size());
        // 准备要给APP相应回去的数据
        List<RecommendUser> result = new ArrayList<>();
        // List<RecommendUser>   按照缘分值排好的有序的
        // 0 -- 9  40条
        // recommendUserList.size() == 50
        // randomInt(0, recommendUserList.size());  从MongoDB查询的结果集中随机10条
        for (int i = 0; i < showCount; i++) {
            //TODO 可能重复
            int index = RandomUtil.randomInt(0, recommendUserList.size());
            RecommendUser recommendUser = recommendUserList.get(index);
            result.add(recommendUser);
            // JDK 里面的方法
            // Collections.shuffle(recommendUserList);   //洗牌  直接打乱
        }

        List<Object> userIdList = CollUtil.getFieldValues(result, "userId");
        // 查询tb_user_info
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());// 推荐的用户ID
            todayBest.setAge(userInfo.getAge()); // 推荐的用户的年龄
            todayBest.setAvatar(userInfo.getLogo());// 推荐用户的头像
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
            todayBest.setFateValue(0L);
            todayBests.add(todayBest);
        }
        // todayBests 只有10条
        return todayBests;
    }

    public Boolean likeUser(Long likeUserId) {
        // 获取登录人的ID
        User user = UserThreadLocal.get();
        Boolean result = this.userLikeApi.likeUser(user.getId(), likeUserId);
        if (!result) {
            return false;
        }

        // 是不是互相喜欢
        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            // 相互喜欢成为好友  自动的成为好友
            // 往MongoDB中好友表中添加  2条记录  给环信发送一个添加好友的请求
            this.imService.contactUser(likeUserId);
        }
        return true;
    }

    public Boolean notLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.notLikeUser(user.getId(), likeUserId);
    }
}
